package com.xinxin.base.util.legacy;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

/**
 * @Auther: xinxin818
 * @Date: 2019/12/16 16:02
 * @Description:
 */
@Slf4j
public class QrCodeUitls {

	/**
	 * 生成二维码
	 *
	 * @return
	 */
	public static String encodeQRCode(String text, String path) {
		int width = 300;
		int height = 300;
		String format = "png";
		//定义二维码的参数
		HashMap hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		hints.put(EncodeHintType.MARGIN, 2);
		//生成二维码

		BitMatrix bitMatrix = null;
		try {
			bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		Path file = new File(path).toPath();
		try {
			MatrixToImageWriter.writeToPath(bitMatrix, format, file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file.toString();
	}

	/**
	 * 对二维码图片进行解码
	 *
	 * @param filePath 二维码路径
	 * @return 解码后对内容
	 */
	public static String decodeQRCode(String filePath) {
		MultiFormatReader formatReader = new MultiFormatReader();
		File file = new File(filePath);
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

		//定义二维码的参数
		HashMap hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

		//为了解决com.google.zxing.NotFoundException报错问题
		hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);

		//结果展示
		Result result = null;
		try {
			result = formatReader.decode(binaryBitmap, hints);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return result.getText();
	}


}
